import Taro, { Component, Config } from '@tarojs/taro'
import { View, Image, Text, Swiper, SwiperItem, ScrollView } from '@tarojs/components'
import { AtTabs, AtTabsPane, AtIcon } from 'taro-ui'
import { observer, inject } from '@tarojs/mobx'

import './index.scss'
import RecommendStore from '../../stores/recommendStore';
import Stores from '../../stores/storeIdentifier';
import { RecommendItemListDto } from '../../services/recommend/dto/recommendItemListDto';
import { PagedList } from '../../services/dto/pagedList';
import { ProductListDto } from '../../services/product/dto/productListDto';
import ProductStore from '../../stores/productStore';
import CategoryStore from '../../stores/categoryStore';
import { CategoryListDto } from '../../services/category/dto/categoryListDto';
import { RecommendPagedQueryDto } from '../../services/recommend/dto/recommendPagedQueryDto';
import TabBar from '../../component/tabBar/tabBar';

export interface IIndexProps {
  recommendStore: RecommendStore,
  productStore: ProductStore,
  categoryStore: CategoryStore
}

@inject(Stores.RecommendStore, Stores.ProductStore, Stores.CategoryStore)
@observer
class Index extends Component<IIndexProps> {

  /**
   * 指定config的类型声明为: Taro.Config
   *
   * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
   * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
   * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
   */
  config: Config = {
    navigationBarTitleText: '分类'
  }

  recommends: RecommendItemListDto[] = []
  products: PagedList<ProductListDto>
  categoryList: CategoryListDto[] = []
  list: any[] = []
  currentCategory: number[] = []
  async componentWillMount() {
    await this.getCategories()
  }

  async getCategories() {
    await this.props.categoryStore!.getCategoriesAsync({ moduleTypeId: '100401' });
    const { categoryList } = this.props.categoryStore
    this.categoryList = categoryList;

    this.categoryList.map(async (item) => {
      this.list.push({ title: item.displayName, id: item.id })
    })
    if (this.categoryList && this.categoryList.length) {
      this.currentCategory = [this.categoryList[0].id];
      await this.getRecommendItemPagedList(this.categoryList[0].name)
    }
    this.setState({}, async () => {
      await this.getProducts();
    });
  }

  state = {
    sorting: 'displayOrder desc',
    skipCount: 0,
    maxResultCount: 10,
    needload: true,
    current: 0
  }

  async getProducts() {
    await this.props.productStore.getProductPagedListAsync({
      sorting: this.state.sorting,
      maxResultCount: this.state.maxResultCount,
      skipCount: this.state.skipCount,
      categoryIds: this.currentCategory
    });
    const { products } = this.props.productStore!;
    let currentCategory = this.categoryList.find(m => m.id == this.currentCategory[0]);
    let needload = true;
    if (currentCategory) {
      if (currentCategory.products) {
        currentCategory.products.currentPage = products.currentPage;
        currentCategory.products.skipCount = products.skipCount;
        currentCategory.products.totalCount = products.totalCount;
        currentCategory.products.totalPages = products.totalPages;
        currentCategory.products.maxResultCount = products.maxResultCount;
        currentCategory.products.items = [...currentCategory.products.items, ...products.items]
        needload = !(currentCategory.products.items.length >= currentCategory.products.totalCount);
      } else {
        currentCategory.products = products;
        needload = true;
      }
    }
    this.setState({ needload: needload })
  }

  onScrollToLower = async () => {
    this.setState({ skipCount: this.state.skipCount + this.state.maxResultCount }, async () => {
      if (this.state.needload) {
        await this.getProducts()
      }
    })
  };
  componentWillReact() {
    console.log('componentWillReact')
  }

  getRecommendItemPagedList = async (cName: string) => {
    await this.props.recommendStore.getRecommendItemPagedList({ recommendIds: ['category_banner_' + cName], skipCount: 0, maxResultCount: 10 })
    this.recommends = this.props.recommendStore.recommends
    this.setState({})
  }

  constructor(props: any) {
    super(props)
  }

  async handleClick(value) {
    if (this.state.current == value) {
      return
    }
    let category = this.categoryList[value];
    this.currentCategory = [category.id];
    await this.getRecommendItemPagedList(category.name);
    if (category.products) {
      category.products.currentPage = 0;
      category.products.skipCount = 0;
      category.products.totalCount = 0;
      category.products.totalPages = 0;
      category.products.maxResultCount = 0;
      category.products.items = []
    }
    this.setState({
      current: value,
      skipCount: 0,
      needload: true
    }, async () => {
      await this.getProducts();
    })
  }


  gotoProduct(id) {
    console.log(this.$router.params.type)
    Taro.navigateTo({ url: '/pages/product/index?id=' + id + '&type=' + this.$router.params.type })
  }

  onShareAppMessage() {
    let tmpPath = '/pages/category/index'
    return {
      title: '',
      path: tmpPath,
      success: function (res) {
        console.log('success')
      },
      fail: function (res) {
        console.log('fail')
      },
      complete: function () {
        console.log('complete');
      }
    }
  }

  search() {
    Taro.navigateTo({
      url: '/pages/product/list'
    })
  }

  render() {

    return (
      <View className='category-wrap'>
        <View className='search-box' onClick={this.search}>
          <View className='search-inner'>
            <AtIcon className='search-icon' value='search' size='16' color='#666' />
            <Text>搜索</Text>
          </View>
        </View>
        <AtTabs
          className='category-tab'
          current={this.state.current}
          height='100%'
          scroll
          tabDirection='vertical'
          tabList={this.list}
          onClick={this.handleClick.bind(this)}>
          {
            this.categoryList.map((item, index) => (
              <AtTabsPane tabDirection='vertical' key={index} current={this.state.current} index={index}>
                <ScrollView
                  className='scrollview'
                  scrollY
                  scrollWithAnimation
                  style='height: 100%'
                  onScrollToLower={this.onScrollToLower}
                >
                  {this.recommends && this.recommends.length > 0 &&
                    <Swiper
                      className='category-slide'
                      indicatorColor='#999'
                      indicatorActiveColor='#333'
                      circular
                      indicatorDots
                      autoplay>
                      {
                        this.recommends.map((recommend) => (
                          <SwiperItem>
                            {recommend.itemId || recommend.linkUrl &&
                              <Image mode='aspectFill'
                                src={recommend.imageUrl}
                                onClick={this.gotoProduct.bind(this,recommend.linkUrl)}
                              />
                            }
                            {!recommend.itemId && !recommend.linkUrl &&
                              <Image mode='aspectFill'
                                src={recommend.imageUrl}
                              />
                            }
                          </SwiperItem>
                        ))
                      }
                    </Swiper>
                  }
                  <View className='pro-list'>
                    {item.products && item.products.items && item.products.items.map((product, proIndex) => (
                      <View className='pro-item' key={proIndex} onClick={this.gotoProduct.bind(this, product.id)}>
                        <Image className='pro-img' mode='aspectFill' src={product.featuredImageUrl} />
                        <View className='pro-title'>{product.name}</View>
                        <View className='pro-price'>
                          <Text className='now-price'>￥{product.price}</Text>
                        </View>
                      </View>
                    ))}
                  </View>
                </ScrollView>

              </AtTabsPane>
            ))
          }
        </AtTabs>
        <TabBar nowPage='index' />
      </View>
    )
  }
}

export default Index
